package com.example.qiniupload.controller;

import com.example.qiniupload.dto.UploadResponse;
import com.example.qiniupload.service.QiniuService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/upload")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class UploadController {
    
    private final QiniuService qiniuService;
    
    /**
     * 上传图片到七牛云
     * 
     * @param file 要上传的图片文件
     * @return 上传结果
     */
    @PostMapping(value = "/image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

    public ResponseEntity<UploadResponse> uploadImage(

            @RequestParam("file") MultipartFile file) {
        
        log.info("接收到图片上传请求，文件名: {}, 大小: {} bytes", 
                file.getOriginalFilename(), file.getSize());
        
        UploadResponse response = qiniuService.uploadFile(file);
        
        if (response.isSuccess()) {
            log.info("图片上传成功，URL: {}", response.getUrl());
            return ResponseEntity.ok(response);
        } else {
            log.error("图片上传失败: {}", response.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 上传文件到七牛云
     * 
     * @param file 要上传的文件
     * @return 上传结果
     */
    @PostMapping(value = "/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

    public ResponseEntity<UploadResponse> uploadFile(

            @RequestParam("file") MultipartFile file) {
        
        log.info("接收到文件上传请求，文件名: {}, 大小: {} bytes", 
                file.getOriginalFilename(), file.getSize());
        
        UploadResponse response = qiniuService.uploadFile(file);
        
        if (response.isSuccess()) {
            log.info("文件上传成功，URL: {}", response.getUrl());
            return ResponseEntity.ok(response);
        } else {
            log.error("文件上传失败: {}", response.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 健康检查接口
     * 
     * @return 健康状态
     */
    @GetMapping("/health")

    public ResponseEntity<String> health() {
        return ResponseEntity.ok("UP");
    }
}
